package zhtt.controller;

import net.sf.jasperreports.engine.JasperRunManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;

@RestController
@RequestMapping("/user")
public class MysqlController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @RequestMapping("/report03")
    public String report03(final ModelMap modelMap, HttpServletRequest request, HttpServletResponse resp) throws IOException, SQLException {
        resp.setContentType("application/pdf");
        ServletOutputStream output= resp.getOutputStream();
        InputStream reportStream = request.getServletContext().getResourceAsStream("/WEB-INF/classes/reports/report3-table.jasper");
        Connection connection = jdbcTemplate.getDataSource().getConnection();
        HashMap parameterMap = new HashMap();
        parameterMap.put("title", new String("%1"));
        try{
            JasperRunManager.runReportToPdfStream(reportStream,output,parameterMap,connection);
            //JasperExportManager.exportReportToHtmlFile();
            connection.close();
            output.flush();
            output.close();
        }catch(Exception e){
            e.printStackTrace();
            StringWriter stringWriter = new StringWriter();
            PrintWriter printWriter = new PrintWriter(stringWriter);
            e.printStackTrace(printWriter);
            resp.setContentType("text/plain");
            resp.getOutputStream().print(stringWriter.toString());
        }
        return "iReportView";
    }

}
